package com.office.onlineInformation.draftBox.service.impl;

import com.office.onlineInformation.draftBox.pojo.MessageSearch;
import com.office.onlineInformation.draftBox.service.MessageSearchService;
import com.office.personalOffice.personalInfo.model.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author shkstart
 * @create 2023-08-02 17:29
 */
@Service
@Slf4j
public class MessageSearchServiceImpl implements MessageSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param createdId
     */
    @Override
    @Async
    public void insert(String keyword, Integer createdId) {
        //1.查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("createdId").is(createdId).and("keyword").is(keyword));
        MessageSearch messageSearch = mongoTemplate.findOne(query, MessageSearch.class);

        //2.存在 更新创建时间
        if(messageSearch != null){
            messageSearch.setCreatedTime(new Date());
            mongoTemplate.save(messageSearch);
            return;
        }

        //3.不存在，判断当前历史记录总数量是否超过10
        messageSearch = new MessageSearch();
        messageSearch.setCreatedId(createdId);
        messageSearch.setKeyword(keyword);
        messageSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("createdId").is(createdId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<MessageSearch> apUserSearchList = mongoTemplate.find(query1, MessageSearch.class);

        if(apUserSearchList == null || apUserSearchList.size() < 10){
            mongoTemplate.save(messageSearch);
        }else {
            MessageSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),messageSearch);
        }
    }


}
